package com.order.api.interceptor;

import com.order.api.constant.BaseException;
import com.order.api.constant.ResultValueEnum;
import com.order.api.dao.UsersDao;
import com.order.api.po.Users;
import com.order.api.service.TokenService;
import com.order.api.target.Authorization;
import com.order.api.util.ThreadLocalUtil;
import com.order.api.vo.TokenModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class AuthorizationInterceptor implements HandlerInterceptor {

    @Autowired
    private UsersDao usersDao;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ThreadLocalUtil threadLocalUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        TokenModel model = tokenService.getToken(request.getHeader("Authorization"));

        if (model != null && tokenService.checkToken(model)) {
            threadLocalUtil.setToken(model.getToken());
            threadLocalUtil.setUserId(model.getUserId());
            Users users = usersDao.selectByPrimaryKey(model.getUserId());
            if (users != null) {
                return true;
            }
        } else {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            if (method.getAnnotation(Authorization.class) != null) {
                throw new BaseException(ResultValueEnum.NO_LOGIN, ResultValueEnum.NO_LOGIN.getTitle());
            }
        }
        return true;


    }
}
